package com.chris.homecare.utils
{
	import com.chris.homecare.data.IDataObject;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;

	public class FileDownloader
	{
		private var remotePath:String;
		private var localPath:String;
		private var dataObject:IDataObject;
		
		public function FileDownloader(remotePath:String, localPath:String, dataObject:IDataObject)
		{
			this.remotePath = remotePath;
			this.localPath = "images/"+localPath;
			this.dataObject = dataObject;
			
			downloadFile();
		}
		
		private function downloadFile():void
		{
			var loader:URLLoader = new URLLoader();
			loader.dataFormat = URLLoaderDataFormat.BINARY;
			loader.addEventListener(IOErrorEvent.IO_ERROR, onDownloadError);
			loader.addEventListener(Event.COMPLETE, onDownloadComplete);
			loader.load(new URLRequest(remotePath));
		}
		
		protected function onDownloadComplete(event:Event):void
		{
			var file:File = File.applicationStorageDirectory.resolvePath(localPath);
			var ba:ByteArray  = event.target.data as ByteArray;
			var fileStream:FileStream = new FileStream();
			fileStream.addEventListener(IOErrorEvent.IO_ERROR, onDownloadError);
			fileStream.open(file, FileMode.WRITE);               
			fileStream.writeBytes(ba);
			fileStream.close();
			
			dataObject.imageUrl = localPath;
			dataObject.storeData();
		}
		
		protected function onDownloadError(event:IOErrorEvent):void
		{
			dataObject.imageUrl = "";
			dataObject.storeData();
			trace("File download Error: " +event.text);
		}
	}
}